package pyip.lib.javalearn.thread.join;

import pyip.lib.javalearn.Timer;

/**
 * t.join(timeout) 结束的条件有两个, t.isAlive==false 或 timeout超时.<br>
 * 在 t.isAlive==true 和 timeout未超时的情况下, 在t里面notifyAll唤醒main线程, main线程也会再次进入wait状态(可以参考join源码).
 * @author yepeng
 * @date 2015年4月27日
 */
public class JoinTimeoutDemo implements Runnable {

    public static void main(String[] args) {
        Thread t = new Thread(new JoinTimeoutDemo(), "bejoinThread");
        t.start();
        try {
            System.out.println("main join start" + ", " + Timer.getSecondsString());
            // join的意思是等够这么多毫秒, 在线程isAlive的情况下
            t.join(1000);
            System.out.println("main join finish" + ", " + Timer.getSecondsString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 每秒钟notifyAll一次, 连续10次
     */
    public void run() {
        String name = Thread.currentThread().getName();
        try {
            System.out.println("\t" + name + " start, " + Timer.getSecondsString());
            for (int i = 0; i < 10; i++) {
                Thread.sleep(1000);
                synchronized (Thread.currentThread()) {
                    System.out.println("\t" + name + " notifyAll, " + Timer.getSecondsString());
                    Thread.currentThread().notifyAll();
                }
            }
            System.out.println("\t" + name + " exit, " + Timer.getSecondsString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
